package com.atguigu.lease.web.app.controller.login;



import com.atguigu.lease.common.jwts.JwtUtil;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Tag(name = "登录管理")
@RequestMapping("/app/")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 获取短信验证码
     * @param phone
     * @return
     * @throws Exception
     */
    @GetMapping("login/getCode")
    @Operation(summary = "获取短信验证码")
    public Result getCode(@RequestParam String phone) throws Exception {
        loginService.getCode(phone);
        return Result.ok();
    }

    /**
     *  根据手机号和验证码登录,生成token并返回
     * @param loginVo
     * @return
     */
    @PostMapping("login")
    @Operation(summary = "登录")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        String token=loginService.login(loginVo);
        return Result.ok(token);
    }

    /**
     * 回显用户信息
     * 1.解析accessToken得到userid
     * 2.根据userid获取用户信息
     * 3.封装进userinfoVo，并返回
     * @return
     */
    @GetMapping("info")
    @Operation(summary = "获取登录用户信息")
    public Result<UserInfoVo> info(@RequestHeader("access_token") String accessToken) {
        //解析accessToken得到userid
        Integer userId =Integer.parseInt(JwtUtil.parseToken(accessToken).get("userId")+"");
        //根据userid获取用户信息
        UserInfo userInfo = userInfoService.getById(userId);
        //封装进userinfoVo，并返回
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return Result.ok(userInfoVo);
    }
}
